package com.tledu.dangjian.controller;

import cn.hutool.crypto.SecureUtil;
import com.tledu.dangjian.core.AjaxResult;
import com.tledu.dangjian.core.constants.CommonConstants;
import com.tledu.dangjian.core.constants.ErrorCodeConstants;
import com.tledu.dangjian.model.Role;
import com.tledu.dangjian.model.User;
import com.tledu.dangjian.service.IResourcesService;
import com.tledu.dangjian.service.IUserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cyrus
 */
@Controller
@AllArgsConstructor
public class LoginController {
    private IUserService userService;
    private IResourcesService resourcesService;

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @ResponseBody
    @PostMapping("/login/action")
    public AjaxResult<String> loginAction(String username, String password, HttpSession session) {
        // 登录操作
        User user = userService.login(username, SecureUtil.md5(password));
        if (user == null) {
            // 用户名或者密码错误哦
            return new AjaxResult<>("账号和密码错误", ErrorCodeConstants.USERNAME_PASSWORD_ERROR, null);
        }
        // 登录成功
        session.setAttribute(CommonConstants.LOGIN_USER_SESSION_KEY, user);
        // 根据角色，设置这个用户对应的菜单
        List<Integer> roleIds = new ArrayList<>();
        for (Role role : user.getRoleList()) {
            roleIds.add(role.getRoleId());
        }
        session.setAttribute(CommonConstants.LOGIN_RESOURCE_SESSION_KEY, resourcesService.listByRoleIds(roleIds));
        return new AjaxResult<>("登录成功", null);
    }
}
